
package com.blog.shiro;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.blog.entity.User;
import com.blog.service.UserService;

//import com.blog.entity.Role;
//import com.blog.entity.User;
//import com.blog.service.UserService;


public class MyShiroRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

	@Autowired
	private UserService uesrApplication;

    @Override  
    protected AuthenticationInfo doGetAuthenticationInfo(  
        AuthenticationToken authenticationToken) throws AuthenticationException {  
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken; 
        Subject currentUser = SecurityUtils.getSubject();
        User user=uesrApplication.findByName(token.getUsername()); 
        if(user!=null){  
        	currentUser.getSession().setAttribute(UserService.SESSION_USERINFO, user.getName());
        	currentUser.getSession().setAttribute("userId", user.getId());
        	currentUser.getSession().setAttribute("userName", user.getName());
            return new SimpleAuthenticationInfo(user.getName(), user.getPassword(), getName());  
        }  
        return null;  
    }
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
}
